package org.example.fortest.controller;

import org.example.fortest.common.RestResult;
import org.example.fortest.model.User;
import org.example.fortest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/list")
    public RestResult list(User user, Pageable pageable) {
        RestResult result = RestResult.success();
        int pageNum = pageable.getPageNumber()-1;
        pageNum = pageNum < 0 ? 0 : pageNum;
        pageable = PageRequest.of(pageNum, pageable.getPageSize());
        result.put("data",userService.selectUserList(user,pageable));
        return result;
    }

    @PostMapping("/add")
    public RestResult add(@RequestBody User user) {
        RestResult result = RestResult.success();
        if (userService.checkUserNameUnique(user)){
            return RestResult.error("用户名重复");
        }
        userService.insertUser(user);
        return RestResult.success();
    }

    @PutMapping("/edit")
    public RestResult edit(@RequestBody User user) {
        RestResult result = RestResult.success();
        if (userService.checkUserNameUnique(user)){
            return RestResult.error("用户名重复");
        }
        userService.updataUser(user);
        return RestResult.success();
    }

    @DeleteMapping("/delete/{id}")
    public RestResult delete(@PathVariable Long id) {
        userService.deleteByFlag(id);
        return RestResult.success();
    }
}
